package cn.com.kblog.model;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.kblog.common.Result;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
/**
 *
 *`id` int(11) NOT NULL AUTO_INCREMENT,
  `type_name` varchar(100) DEFAULT NULL,
 */
@TableBind(tableName = "blog_type",pkName="id")
public class BlogType extends Model<BlogType>{
	/** */
	private static final long serialVersionUID = 4229426538804250534L;

	public static final BlogType dao = new BlogType();
	
	
	/**标签名 */
	public static final String TYPE_NAME = "type_name";
	
	
	
	/**
	 * 根据参数返回Blog列表
	 * @param cpage
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param allParams
	 * @return
	 */
	public Page<BlogType> pageQuery(int cpage, int pageSize, String orderField,
		String orderDirection, Map<String, String> allParams) {
		String sql_select = "select * ";
		StringBuffer conf = new StringBuffer(" from blog_type t where 1=1 ");
		List<String> params = new ArrayList<String>();
		if (allParams == null) {
		    allParams = new HashMap<String, String>();
		}
		if (StringKit.notBlank(allParams.get(TYPE_NAME))) {
		    conf.append(" and lower(t.type_name) like ? ");
		    params.add("%"+allParams.get(TYPE_NAME)+"%");
		}
		if (StringKit.notBlank(orderField, orderDirection)) {
		    conf.append(" order by ").append(" t.").append(orderField).append(
			    " ").append(orderDirection);
		}
		return dao.paginate(cpage, pageSize, sql_select, conf.toString(),params.toArray());
	 }
	
	/**
	 * 获得所有标签
	 * @return
	 */
	public List<BlogType> listAll(){
		String sql = "select t.* from blog_type t";
		return dao.find(sql);
	}
	
	
	/**
	 * 保存或者更新
	 * @return
	 */
	public Result saveOrUpdate(){
		Result result = new Result();
		if (getID() == null) {
		   if(this.save()){
			    result.success("添加成功！"); 
		   }else{
			    result.error("添加失败！");
		   }
		   
		} else {
		   if(update()){
			    result.success("更新成功！"); 
		   }else{
			    result.error("更新标签失败！");
		   }
		}
		return result;
	}
	
	
    /**
     * 根据ID删除标签
     * @param id
     * @return
     */
    public Result deleteById(String id) {
    	Result result = new Result();
    	
		if (StringKit.isBlank(id)) {
		     result.success("信息错误！");
		}
		 if(super.deleteById(id)){
			  result.success("删除标签成功！"); 
		 }else{
			  result.error("删除标签失败！");
		 }
		 return result;
    }
    
    /**
     * 标签对应的Blog篇数
     * @return
     */
    public Long getBlogCount(){
    	String sql = "select count(*) from blog where blog_type=?";
    	List<Long> list = Db.query(sql, this.getID());
    	return list.get(0);
    }
    
	public Integer getID() {
		return getInt("id");
	} 
}
